﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Minestorm.Evolved.IoC;
using Minestorm.Evolved.SceneObjects;
using Minestorm.Evolved.Animation;

namespace Minestorm.Evolved.Scenes
{
    public abstract class Scene
    {
        private List<SceneObject> _objects;
        private bool _contentLoaded;

        public Scene(IObjectFactory objectFactory, GraphicsDevice graphicsDevice)
        {
            _contentLoaded = false;

            _objects = new List<SceneObject>();

            ObjectFactory = objectFactory;
            GraphicsDevice = graphicsDevice;

            SpriteBatch = new SpriteBatch(graphicsDevice);

            EasingManager = new EasingManager();
        }

        protected IObjectFactory ObjectFactory { get; private set; }

        public Camera Camera { get; protected set; }

        protected GraphicsDevice GraphicsDevice { get; private set; }

        protected SpriteBatch SpriteBatch { get; private set; }

        public EasingManager EasingManager { get; private set; }

        public void RemoveObject(SceneObject sceneObject)
        {
            _objects.Remove(sceneObject);

            if (_contentLoaded)
                sceneObject.UnloadContent();
        }

        public void AddObject(SceneObject sceneObject)
        {
            sceneObject.ObjectFactory = ObjectFactory;
            sceneObject.GraphicsDevice = GraphicsDevice;
            sceneObject.SpriteBatch = SpriteBatch;
            sceneObject.Scene = this;

            _objects.Add(sceneObject);

            if (_contentLoaded)
                sceneObject.LoadContent();
        }

        public virtual void LoadContent()
        {
            _contentLoaded = true;

            foreach (var sceneObject in _objects)
                sceneObject.LoadContent();
        }

        public virtual void UnloadContent()
        {
            foreach (var sceneObject in _objects)
                sceneObject.UnloadContent();
        }

        public virtual void Update(GameTime gameTime)
        {
            EasingManager.Update(gameTime);

            foreach (var sceneObject in _objects)
                sceneObject.Update(gameTime);
        }

        public virtual void HandleInput(InputState inputState)
        {
            foreach (var sceneObject in _objects)
                sceneObject.HandleInput(inputState);
        }

        public virtual void Draw(GameTime gameTime)
        {
            foreach (var sceneObject in _objects)
                sceneObject.Draw(gameTime);
        }
    }
}
